package com.itheima.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
// 切面类
public class LogAspect {

    // 这里可以直接通过注入的方式获取本次请求的HttpServletRequest对象
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        // 操作人ID  从令牌中获取
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer userId = (Integer) claims.get("id");

        // 操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        // 操作类名
        String className = joinPoint.getTarget().getClass().getName();

        // 操作方法名
        String methodName = joinPoint.getSignature().getName();

        // 操作参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long start = System.currentTimeMillis();
        // 调用原始方法执行
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        // 操作结果
        String resultJson = JSONObject.toJSONString(result);

        // 操作耗时
        long operateTimeMillis = end - start;

        // 记录日志
        OperateLog operateLog = new OperateLog(null, userId, operateTime, methodName, methodParams, methodParams, resultJson, operateTimeMillis);
        operateLogMapper.insert(operateLog);

        log.info("操作日志记录成功，操作人ID：{}，操作时间：{}，操作类名：{}，操作方法名：{}，操作参数：{}，操作结果：{}，操作耗时：{}ms", userId, operateTime, className, methodName, methodParams, resultJson, operateTimeMillis);

        return result;
    }
}
